package com.bo.Controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import com.bo.Entity.CompanyTouch;
import com.bo.Entity.MyImage;
import com.bo.Service.CompanyTouchService;
import com.bo.Validator.CompanyTouchValidator;
import com.bo.util.ImageUtil;
import com.bo.util.SessionUtil;


@Controller
@RequestMapping(value="/main")
@SessionAttributes("companyTouch")
public class CompanyTouchController {

	
	@Autowired
	private CompanyTouchService companyTouchService;
	
	@Autowired
	private CompanyTouchValidator companyTouchValidator;
	

	@RequestMapping(value="/companyTouch.do",method=RequestMethod.GET)
	public String companyInt(Model model,HttpServletRequest request){
		

		CompanyTouch companyTouch=companyTouchService.getCompanyTouch(SessionUtil.getCompanyId(request));
		
		model.addAttribute("companyTouch", companyTouch);
		
		return "companyTouch";
	}
	
	
	
	
	
	@RequestMapping(value="/companyTouch.do",method=RequestMethod.POST)
	public String companyInt(@ModelAttribute("companyTouch") CompanyTouch companyTouch
			,BindingResult result,Model model
			,@RequestParam("file") MultipartFile image
			,HttpServletRequest request,SessionStatus status){
		
		companyTouch.setCompanyId(SessionUtil.getCompanyId(request));
		
		try {
			
			String imageName=ImageUtil.createImageName(image.getContentType());

     		companyTouch.setImage(new MyImage(1,imageName,image.getSize(),image.getInputStream()));	
		  
		    companyTouchValidator.validate(companyTouch, result);
			
			if(result.hasErrors()){
				
				return "companyTouch";
			}

			companyTouchService.update(companyTouch);
			
			status.setComplete();
			
		} catch (IOException e) {
			
			e.printStackTrace();
			
		}
		
	   return "redirect:companyTouch.do";
	}

}
